package cn.wolfcode.service.impl;

import cn.wolfcode.domain.ArticlesItem;
import cn.wolfcode.domain.InMsgEntity;
import cn.wolfcode.domain.OutMsgEntity;
import cn.wolfcode.service.IWebChatService;
import cn.wolfcode.util.MsgType;
import cn.wolfcode.util.WebChatUtil;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

@Service
public class WebChatServiceImpl implements IWebChatService {
    @Override
    public String weChar(String signature, String timestamp, String nonce, String echostr) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = {WebChatUtil.TOKEN,timestamp,nonce};
        Arrays.sort(arr);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return null;
    }

    @Override
    public OutMsgEntity handelMsg(InMsgEntity inMsgEntity) {
        OutMsgEntity outMsgEntity = new OutMsgEntity();
        // 消息发送方
        outMsgEntity.setFromUserName(inMsgEntity.getToUserName());
        // 消息接收方
        outMsgEntity.setToUserName(inMsgEntity.getFromUserName());
        // 消息发送时间
        outMsgEntity.setCreateTime(new Date().getTime());
        // 获取消息类型
        String msgType = inMsgEntity.getMsgType();
        if (MsgType.TEXT.equals(msgType)){
            // 消息类型
            outMsgEntity.setMsgType(MsgType.TEXT);
            // 设置内容
            String content = inMsgEntity.getContent();
            String outContent = "";
            if (content.contains("开班")){
                outContent = "开班xxx";
            }else if (content.contains("地址")){
                outContent = "地址xxx";
            }else {
                outContent = inMsgEntity.getContent();
            }
            // 消息内容
            outMsgEntity.setContent(outContent);
        }else if (MsgType.IMAGE.equals(msgType)){
            // 消息类型
            outMsgEntity.setMsgType(MsgType.IMAGE);
            // 设置图片信息
            outMsgEntity.setMediaId(new String[]{inMsgEntity.getMediaId()});
        }else if (MsgType.EVENT.equals(msgType)){
            if (inMsgEntity.getEvent().equals("subscribe")){
                // 关注
                // 回复图文信息
                outMsgEntity.setArticleCount(1);
                outMsgEntity.setMsgType(MsgType.NEWS);
                ArticlesItem item = new ArticlesItem();
                item.setTitle("叩丁狼学员成长之路");
                item.setDescription("【快来围观——叩丁小狼的日常】");
                item.setPicUrl("https://img.wolfcode.cn//upload/images/slide/20211206/62717b26-6e0e-42c5-a3d9-ab747d3f8bed.jpg");
                item.setUrl("https://www.wolfcode.cn/articlePage.html?id=8448");
                outMsgEntity.setItem(new ArticlesItem[]{item});
            }else {
                // 取消关注
                outMsgEntity.setMsgType(MsgType.TEXT);
            }
        }
        return outMsgEntity;
    }
}
